package net.xo68.destiny.manager.security;


import lombok.extern.slf4j.Slf4j;
import net.xo68.destiny.contract.common.SystemConstants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证过滤器
 * @author wuxie
 * @version 2020-9-14
 */
@Slf4j
public class UserJwtTokenAuthenticationFilter extends OncePerRequestFilter {

    private final UserJwtTokenTemplate tokenTemplate;
    private final AntPathRequestMatcher requestMatcher;

    public UserJwtTokenAuthenticationFilter(AuthenticationManager authenticationManager,UserJwtTokenTemplate tokenTemplate,String apiPattern) {
        this.tokenTemplate = tokenTemplate;
        this.requestMatcher=new AntPathRequestMatcher(apiPattern);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        //api路径跳过验证
        if(requestMatcher.matches(request)){
            chain.doFilter(request, response);
            return;
        }

        String authToken = request.getHeader(SystemConstants.TOKEN_HEADER);
        if (StringUtils.isNotEmpty(authToken) && authToken.startsWith(SystemConstants.TOKEN_PREFIX)) {
            authToken = authToken.substring(SystemConstants.TOKEN_PREFIX.length());
        } else {
            // 不按规范,不允许通过验证
            authToken = null;
            chain.doFilter(request, response);
            return;
        }
        log.debug("request uri:{}", request.getRequestURI());
        //解析jwt令牌，进行安全配置
        if (StringUtils.isNotEmpty(authToken)){
            try {
                SecurityUser securityUser=tokenTemplate.parse(authToken);
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(securityUser, authToken, securityUser.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                //Authentication authentication = this.authenticationManager.authenticate(usernamePasswordAuthenticationToken);
                log.debug("Authenticated user {}, setting security context", securityUser.getUsername());
                SecurityContextHolder.getContext().setAuthentication(authentication);
                //chain.doFilter(request, response);
            }catch (Exception e){
                log.warn("{},{}","令牌解析异常或过期",e.getMessage());
                //chain.doFilter(request, response);
            }
        }
        chain.doFilter(request, response);

    }
}
